import { Directive } from "@angular/core";
import {
  ValidatorFn,
  AbstractControl,
  NG_VALIDATORS,
  Validator,
  ValidationErrors
} from "@angular/forms";

@Directive({
  selector: "[appNameValidator]",
  providers: [
    {
      provide: NG_VALIDATORS,
      useExisting: NameValidatorDirective,
      multi: true
    }
  ]
})
export class NameValidatorDirective implements Validator {
  constructor() {}

  validate(control: AbstractControl): ValidationErrors | null {
    return nameValidator()(control);
  }
}

export function nameValidator(): ValidatorFn {
  return (control: AbstractControl): { [key: string]: any } | null => {
    const nameValidator = /^\w+$/;
    const isValid = nameValidator.test(control.value);
    return isValid ? null : { nameValidator: { value: control.value } };
  };
}
